﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Songhay.BiggestBox.Portable.Modules.ModelContext.Tests.Extensions
{
    /// <summary>
    /// Extensions of test context
    /// </summary>
    public static class TestContextExtensions
    {
        /// <summary>
        /// Test context extensions: should load remote XML.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="href">The href.</param>
        public static async Task<XDocument> ShouldLoadRemoteXml(this TestContext context, string href)
        {
            var uri = new Uri(href);
            var client = new HttpClient();
            var result = await client.GetAsync(uri);

            Assert.IsTrue(result.IsSuccessStatusCode,
                string.Format("The expected success status code is not here: {0}, reason: {1}",
                    result.StatusCode, result.ReasonPhrase));

            var xml = await result.Content.ReadAsStringAsync();
            Assert.IsNotNull(xml, "The expected XML is not here.");

            return XDocument.Parse(xml);
        }

        /// <summary>
        /// Test context extensions: should write XML.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="xDoc">The x document.</param>
        /// <param name="path">The path.</param>
        public static void ShouldWriteXml(this TestContext context, XDocument xDoc, string path)
        {
            var xml = xDoc.ToString();
            FrameworkFileUtility.Write(xml, path);
            context.WriteLine(xml);
        }
    }
}
